//! 数据网关微内核实现
//! 
//! 这是整个系统的核心，协调各个组件的工作：
//! - 插件管理
//! - 事件总线
//! - 资源管理
//! - 配置管理
//! - 安全管理

use std::sync::Arc;
use tokio::sync::RwLock;

use crate::error::{KernelError, Result};
use crate::plugin::{Plugin, PluginManager};
use crate::event::EventBus;
use crate::resource::ResourceManager;
use crate::config::ConfigManager;
use crate::security::SecurityManager;
use crate::query::{Query, QueryResult};

/// 数据网关微内核
pub struct DataGatewayKernel {
    /// 插件管理器
    plugin_manager: Arc<PluginManager>,
    /// 事件总线
    event_bus: Arc<EventBus>,
    /// 资源管理器
    resource_manager: Arc<ResourceManager>,
    /// 配置管理器
    config_manager: Arc<ConfigManager>,
    /// 安全管理器
    security_manager: Arc<SecurityManager>,
    /// 内核状态
    state: Arc<RwLock<KernelState>>,
}

/// 内核状态
#[derive(Debug, Clone)]
pub enum KernelState {
    /// 未初始化
    Uninitialized,
    /// 初始化中
    Initializing,
    /// 运行中
    Running,
    /// 停止中
    Stopping,
    /// 已停止
    Stopped,
    /// 错误状态
    Error(String),
}

/// 内核统计信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KernelStats {
    /// 内核状态
    pub state: String,
    /// 运行时间（秒）
    pub uptime_seconds: u64,
    /// 已加载插件数量
    pub loaded_plugins: usize,
    /// 运行中插件数量
    pub running_plugins: usize,
    /// 处理的查询总数
    pub total_queries: u64,
    /// 成功查询数
    pub successful_queries: u64,
    /// 失败查询数
    pub failed_queries: u64,
    /// 平均查询时间（毫秒）
    pub avg_query_time_ms: f64,
    /// 内存使用量（字节）
    pub memory_usage_bytes: usize,
    /// 最后更新时间
    pub last_updated: chrono::DateTime<chrono::Utc>,
}

impl DataGatewayKernel {
    /// 创建新的微内核实例
    pub async fn new() -> Result<Self> {
        tracing::info!("创建数据网关微内核");
        
        // 创建事件总线
        let event_bus = Arc::new(EventBus::new());
        
        // 创建各个管理器
        let plugin_manager = Arc::new(PluginManager::new(event_bus.clone()));
        let resource_manager = Arc::new(ResourceManager::new());
        let config_manager = Arc::new(ConfigManager::new(event_bus.clone()));
        let security_manager = Arc::new(SecurityManager::new());
        
        let kernel = Self {
            plugin_manager,
            event_bus,
            resource_manager,
            config_manager,
            security_manager,
            state: Arc::new(RwLock::new(KernelState::Uninitialized)),
        };
        
        tracing::info!("微内核创建完成");
        Ok(kernel)
    }
    
    /// 启动微内核
    pub async fn start(&self) -> Result<()> {
        tracing::info!("启动数据网关微内核");
        
        // 更新状态
        {
            let mut state = self.state.write().await;
            *state = KernelState::Initializing;
        }
        
        // 初始化各个组件
        self.resource_manager.initialize().await
            .map_err(|e| KernelError::internal(format!("资源管理器初始化失败: {}", e)))?;
        
        self.security_manager.start().await
            .map_err(|e| KernelError::internal(format!("安全管理器启动失败: {}", e)))?;
        
        // 加载核心插件
        self.load_core_plugins().await?;
        
        // 更新状态
        {
            let mut state = self.state.write().await;
            *state = KernelState::Running;
        }
        
        tracing::info!("数据网关微内核启动完成");
        Ok(())
    }
    
    /// 停止微内核
    pub async fn stop(&self) -> Result<()> {
        tracing::info!("停止数据网关微内核");
        
        // 更新状态
        {
            let mut state = self.state.write().await;
            *state = KernelState::Stopping;
        }
        
        // 停止所有插件
        let plugins = self.plugin_manager.list_plugins().await;
        for plugin_metadata in plugins {
            if let Err(e) = self.plugin_manager.stop_plugin(&plugin_metadata.id).await {
                tracing::warn!("停止插件失败 {}: {}", plugin_metadata.id, e);
            }
        }
        
        // 卸载所有插件
        for plugin_metadata in self.plugin_manager.list_plugins().await {
            if let Err(e) = self.plugin_manager.unregister_plugin(&plugin_metadata.id).await {
                tracing::warn!("卸载插件失败 {}: {}", plugin_metadata.id, e);
            }
        }
        
        // 更新状态
        {
            let mut state = self.state.write().await;
            *state = KernelState::Stopped;
        }
        
        tracing::info!("数据网关微内核已停止");
        Ok(())
    }
    
    /// 处理查询请求
    pub async fn handle_query(&self, query: Query) -> Result<QueryResult> {
        // 检查内核状态
        {
            let state = self.state.read().await;
            if !matches!(*state, KernelState::Running) {
                return Err(KernelError::internal("内核未运行"));
            }
        }
        
        tracing::debug!("处理查询请求: {}", query.id);
        
        // 通过插件管理器处理查询
        let result = self.plugin_manager.handle_query(query).await?;
        
        tracing::debug!("查询处理完成: {}", result.query_id);
        Ok(result)
    }
    
    /// 注册插件
    pub async fn register_plugin(&self, plugin: Box<dyn Plugin>) -> Result<()> {
        self.plugin_manager.register_plugin(plugin).await
    }
    
    /// 启动插件
    pub async fn start_plugin(&self, plugin_id: &str) -> Result<()> {
        self.plugin_manager.start_plugin(plugin_id).await
    }
    
    /// 停止插件
    pub async fn stop_plugin(&self, plugin_id: &str) -> Result<()> {
        self.plugin_manager.stop_plugin(plugin_id).await
    }
    
    /// 卸载插件
    pub async fn unregister_plugin(&self, plugin_id: &str) -> Result<()> {
        self.plugin_manager.unregister_plugin(plugin_id).await
    }
    
    /// 获取内核状态
    pub async fn get_state(&self) -> KernelState {
        let state = self.state.read().await;
        state.clone()
    }
    
    /// 获取内核统计信息
    pub async fn get_stats(&self) -> Result<KernelStats> {
        let plugins = self.plugin_manager.list_plugins().await;
        let loaded_plugins = plugins.len();
        
        // 统计运行中的插件
        let mut running_plugins = 0;
        for plugin_metadata in &plugins {
            if let Some(status) = self.plugin_manager.get_plugin_status(&plugin_metadata.id).await {
                if matches!(status, crate::plugin::PluginStatus::Running) {
                    running_plugins += 1;
                }
            }
        }
        
        // 获取资源使用情况
        let resource_usage = self.resource_manager.get_all_resource_usage().await;
        let memory_usage = resource_usage.get(&crate::resource::ResourceType::Memory)
            .map(|usage| usage.current_usage)
            .unwrap_or(0);
        
        let state = self.get_state().await;
        let state_str = match state {
            KernelState::Uninitialized => "uninitialized",
            KernelState::Initializing => "initializing",
            KernelState::Running => "running",
            KernelState::Stopping => "stopping",
            KernelState::Stopped => "stopped",
            KernelState::Error(_) => "error",
        }.to_string();
        
        Ok(KernelStats {
            state: state_str,
            uptime_seconds: 0, // TODO: 实现运行时间统计
            loaded_plugins,
            running_plugins,
            total_queries: 0, // TODO: 实现查询统计
            successful_queries: 0,
            failed_queries: 0,
            avg_query_time_ms: 0.0,
            memory_usage_bytes: memory_usage,
            last_updated: chrono::Utc::now(),
        })
    }
    
    /// 获取插件管理器
    pub fn plugin_manager(&self) -> Arc<PluginManager> {
        self.plugin_manager.clone()
    }
    
    /// 获取事件总线
    pub fn event_bus(&self) -> Arc<EventBus> {
        self.event_bus.clone()
    }
    
    /// 获取资源管理器
    pub fn resource_manager(&self) -> Arc<ResourceManager> {
        self.resource_manager.clone()
    }
    
    /// 获取配置管理器
    pub fn config_manager(&self) -> Arc<ConfigManager> {
        self.config_manager.clone()
    }
    
    /// 获取安全管理器
    pub fn security_manager(&self) -> Arc<SecurityManager> {
        self.security_manager.clone()
    }
    
    /// 加载核心插件
    async fn load_core_plugins(&self) -> Result<()> {
        tracing::info!("加载核心插件");

        // TODO: 实现核心插件的加载
        // 这里应该加载：
        // 1. SQL查询引擎插件
        // 2. Flight SQL服务器插件
        // 3. 基础数据源插件
        // 4. 认证授权插件

        tracing::info!("核心插件加载完成");
        Ok(())
    }
    
    /// 健康检查
    pub async fn health_check(&self) -> Result<HealthCheckResult> {
        let state = self.get_state().await;
        let stats = self.get_stats().await?;
        
        let status = match state {
            KernelState::Running => HealthStatus::Healthy,
            KernelState::Initializing => HealthStatus::Warning,
            KernelState::Stopping => HealthStatus::Warning,
            KernelState::Stopped => HealthStatus::Critical,
            KernelState::Error(_) => HealthStatus::Critical,
            KernelState::Uninitialized => HealthStatus::Critical,
        };
        
        let mut checks = Vec::new();
        
        // 检查插件状态
        checks.push(ComponentHealth {
            component: "plugins".to_string(),
            status: if stats.running_plugins > 0 { 
                HealthStatus::Healthy 
            } else { 
                HealthStatus::Warning 
            },
            message: format!("{}/{} 插件运行中", stats.running_plugins, stats.loaded_plugins),
        });
        
        // 检查内存使用
        let memory_status = if stats.memory_usage_bytes < 1024 * 1024 * 1024 { // < 1GB
            HealthStatus::Healthy
        } else if stats.memory_usage_bytes < 2 * 1024 * 1024 * 1024 { // < 2GB
            HealthStatus::Warning
        } else {
            HealthStatus::Critical
        };
        
        checks.push(ComponentHealth {
            component: "memory".to_string(),
            status: memory_status,
            message: format!("内存使用: {} MB", stats.memory_usage_bytes / 1024 / 1024),
        });
        
        Ok(HealthCheckResult {
            overall_status: status,
            components: checks,
            timestamp: chrono::Utc::now(),
        })
    }
}

/// 健康检查结果
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HealthCheckResult {
    pub overall_status: HealthStatus,
    pub components: Vec<ComponentHealth>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// 组件健康状态
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ComponentHealth {
    pub component: String,
    pub status: HealthStatus,
    pub message: String,
}

/// 健康状态
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum HealthStatus {
    Healthy,
    Warning,
    Critical,
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_kernel_lifecycle() {
        let kernel = DataGatewayKernel::new().await.unwrap();
        
        // 检查初始状态
        let state = kernel.get_state().await;
        assert!(matches!(state, KernelState::Uninitialized));
        
        // 启动内核
        kernel.start().await.unwrap();
        
        // 检查运行状态
        let state = kernel.get_state().await;
        assert!(matches!(state, KernelState::Running));
        
        // 获取统计信息
        let stats = kernel.get_stats().await.unwrap();
        assert_eq!(stats.state, "running");
        
        // 健康检查
        let health = kernel.health_check().await.unwrap();
        assert!(matches!(health.overall_status, HealthStatus::Healthy | HealthStatus::Warning));
        
        // 停止内核
        kernel.stop().await.unwrap();
        
        // 检查停止状态
        let state = kernel.get_state().await;
        assert!(matches!(state, KernelState::Stopped));
    }
}
